package stater

import (
	// "bp/cache"
	"bp/internal/util"
	"context"
)

type NMemberGotCoupon struct {
	CouponID       int64
	DistributionID int64
	MemberID       int64
}

func (s *StaterComServiceImp) runMemberGotCouponStatWorkers(max uint32) (chans []chan *NMemberGotCoupon) {
	for i := 0; i < int(max); i++ {
		ch := make(chan *NMemberGotCoupon)
		s.slog.Infof("领券引起的统计任务 worker:%d", i+1)
		go s.doMemberGotCouponStatTask(ch)
		chans = append(chans, ch)
	}
	return
}

func (s *StaterComServiceImp) doMemberGotCouponStatTask(ch <-chan *NMemberGotCoupon) {
	ctx := context.Background()
	var err error
	for ptr := range ch {
		// 这里开始真正的执行统计任务
		q := s.dao.Q
		err = s.entityHub.CouponService.RefreshCouponDistributionStatSinceMemberGotCoupon(ctx, q, ptr.DistributionID)
		if err != nil {
			s.slog.Errorf("RefreshCouponDistributionStatSinceMemberGotCoupon err:%s", err.Error())
		}
		err = s.entityHub.CouponService.RefreshCouponStatSinceMemberGotCoupon(ctx, q, ptr.CouponID)
		if err != nil {
			s.slog.Errorf("RefreshCouponStatSinceMemberGotCoupon err:%s", err.Error())
		}
		// err := s.entityHub.CouponService.Up(ctx, q, ptr)
		s.slog.Infof("刷新领取券后的券统计、券投放统计")
	}
}

func (s *StaterComServiceImp) GetMemberGotCouponStatWorker() (ch chan<- *NMemberGotCoupon) {
	upper := len(s.memberGotCouponNotifyChans) - 1
	ch = s.memberGotCouponNotifyChans[util.RandomInt(0, int32(upper))]
	if ch != nil {
		return
	}
	return
}
